package com.zimper.web.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zimper.model.User;

public class JspServlet extends HttpServlet {
	private static final long serialVersionUID = -1256437878850199526L;
	private final String WEB_INF = "/WEB-INF";

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String submitFlag = request.getParameter("submitFlag");
		if ("checkLogin".equals(submitFlag)) {
			login(request, response);
			return;
		} else {
			toLogin(request, response);
			return;
		}
	}

	private void toLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = WEB_INF+ "/pages/login.jsp";
		request.getRequestDispatcher(url).forward(request, response);
	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		if (checkUser(username, password)) {
			String url = WEB_INF+ "/pages/success.jsp";
			request.getRequestDispatcher(url).forward(request, response);
		} else {
			request.setAttribute("user", user);
			request.setAttribute("msg", "用户名或者密码错误，请重新登录！");
			toLogin(request, response);
			return;
		}
	}
	
	protected boolean checkUser(String username,String password) {
		if("yaoper".equals(username) && "12345".equals(password)){
			return true;
		}else{
			return false;
		}
	}
}